package com.cool.springcloud.controller;

import com.cool.springcloud.dao.PaymentDao;
import com.cool.springcloud.entity.PaymentEntity;
import com.cool.springcloud.utils.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author ifredomvip@gmail.com
 * @Date 2022/8/18 14:14
 * @Version 1.0.0
 * @Description
 **/
@Slf4j
@RestController
@RequestMapping("/payment")
public class PaymentController {
    @Autowired
    private PaymentDao paymentDao;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String serverPort;

    @PostMapping("/insertOne")
    public AjaxResult<Integer> insertOne(@RequestBody PaymentEntity payment) throws InterruptedException {

        int result = paymentDao.insertPayment(payment);

//        Thread.sleep(5000L);
        return new AjaxResult<>(200, "插入成功,ServerPort:" + serverPort, result);
    }

    @GetMapping("/getOne/{id}")
    public AjaxResult<PaymentEntity> getOne(@PathVariable("id") Long id) {
        PaymentEntity payment = paymentDao.getPaymentById(id);
        System.out.println(payment);
        return new AjaxResult<>(200, "success,ServerPort:" + serverPort, payment);
    }

    @GetMapping("/discovery")
    public AjaxResult<List> discoveryRestful() {
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("service 服务名称: " + service);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info("instances 实例名称: " + instance);
        }
        return new AjaxResult<List>(200, "实例", instances);
    }

    @GetMapping("/timeout")
    public AjaxResult<String> timeoutRestful() {
        try {
            TimeUnit.SECONDS.sleep(5L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new AjaxResult<String>(200, "实例", serverPort);
    }

}
